<?php

namespace App\Morefun\Quiz;

use App\Contracts\Repositories\Quiz\OptionRepository as OptionRepositoryContact;
use App\Entities\QuizOption;

class OptionRepository implements OptionRepositoryContact
{
    public function create(array $data)
    {
        $data = array_merge([
            'sort' => 0,
            'resource' => '',
        ], $data);
        $option = new QuizOption();
        $option->fill($data);
        if($option->save()){
            return $option->id;
        }

        return false;
    }

    public function findByQuizId($quizId, array $columns = ['*'])
    {
        return QuizOption::query()->where('quiz_id', $quizId)
            ->orderBy('created_at', 'ASC')
            ->get($columns);
    }
    public function findTextByQuizId($quizId, $text)
    {
        return QuizOption::query()
            ->where('quiz_id', $quizId)
            ->where('text', $text)
            ->first();
    }

    public function findMAXSortByQuizId($quizId)
    {
        return QuizOption::query()
            ->where('quiz_id', $quizId)
            ->max('sort');
    }

    public function find($id, array $columns = ['*'])
    {
        return QuizOption::query()->where('id', $id)->first($columns);
    }

    public function update($id, array $data)
    {
        $option = QuizOption::query()->where('id', $id)->first();

        if (null === $option) {
            return false;
        }

        $option->fill($data);

        return $option->save();
    }

    public function delete($id)
    {
        return QuizOption::query()->where('id', $id)->delete();
    }

    public function deleteByQuizId($quizId)
    {
        return QuizOption::query()->where('quiz_id', $quizId)->delete();
    }

}
